package com.mdp.oauth2.server.integration.authenticator;

import com.mdp.core.utils.RequestUtils;
import com.mdp.oauth2.server.LockUtil;
import com.mdp.oauth2.server.entity.SysUser;
import com.mdp.oauth2.server.integration.IntegrationParams;
import com.mdp.oauth2.server.service.SysUserService;
import com.mdp.oauth2.server.service.UserBaseInfoQueryService;
import com.mdp.safe.client.dict.AuthType;
import com.mdp.safe.client.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 默认登录处理,密码方式
 * 格式 url: http://${domain}/api/m1/oauth2/oauth/token?grant_type=password&username=${username}&password=${前端密码MD5加密后的密码}&scope=all
 * @author chenyc
 * @date 2021-01-12
 **/
@Component
public class PasswordDisplayUseridAuthenticator extends AuthenticatorAdapter{



    @Override
    public User authenticate(IntegrationParams integrationParams) {
        User user= getByUserloginid(integrationParams.getUserloginid(),integrationParams);
        if(user!=null && "1".equals(user.get("locked"))) {
            String lockType = (String) user.get("lockType");
            String lockRemark = (String) user.get("lockRemark");
            String statusText = LockUtil.getLockMsgByLockType(lockType);
            if (!StringUtils.hasText(statusText)) {
                statusText = "lock-type-9 账户已锁定";
            }
            HttpHeaders httpHeaders = new HttpHeaders();
            throw new WebClientResponseException(401, statusText, httpHeaders, statusText.getBytes(), null, null);
        }
        return user;
    }

    /**
     * 查找用户基础信息
     * @param displayUserid 前台登陆编号
     * @return
     */
    public User getByUserloginid(String displayUserid,IntegrationParams integrationParams){
        List<User> users= userBaseInfoQueryService.queryByUserloginid(displayUserid,"all",integrationParams.getDatas());
        if(users!=null && users.size()>1){
            Optional<User> displayUseridSame=users.stream().filter(k->displayUserid.equals(k.getDisplayUserid())).findAny();
            if(displayUseridSame.isPresent()){
                return displayUseridSame.get();
            }
        }
        //为了测试方便，将密码设置为与前端上送的密码一致
        //user.setPassword(passwordEncoder.encode(integrationParams.getAuthParameter("password")));
        return SysUserService.autoTestUser(users,integrationParams.getUserType(),integrationParams.getAuthParameter("branchId"));
     }

    @Override
    public boolean supportAuthType(IntegrationParams integrationParams) {
        return AuthType.password_display_userid.name().equals(integrationParams.getAuthType());
    }
}
